import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Space,
  Popconfirm,
  message,
  Card,
  Row,
  Col,
  Tag,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'umi';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

// 数据类型定义
interface UserItem {
  id: string;
  name: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  status: 'active' | 'inactive';
  createTime: string;
  lastLoginTime?: string;
}

// 表单数据类型
interface UserFormData {
  name: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  status: 'active' | 'inactive';
}

// 搜索表单类型
interface SearchFormData {
  name?: string;
  department?: string;
  status?: string;
}

const ManualUserList: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 状态管理
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<UserItem[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserItem | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 部门选项
  const departmentOptions = [
    { label: '技术部', value: 'tech' },
    { label: '产品部', value: 'product' },
    { label: '运营部', value: 'operation' },
    { label: '市场部', value: 'marketing' },
    { label: '财务部', value: 'finance' },
  ];

  // 状态选项
  const statusOptions = [
    { label: '活跃', value: 'active' },
    { label: '非活跃', value: 'inactive' },
  ];

  // 模拟API调用
  const fetchUsers = async (params: {
    current: number;
    pageSize: number;
    name?: string;
    department?: string;
    status?: string;
  }) => {
    setLoading(true);
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟数据
      const mockData: UserItem[] = Array.from({ length: 50 }, (_, index) => ({
        id: `user_${index + 1}`,
        name: `用户${index + 1}`,
        email: `user${index + 1}@example.com`,
        phone: `138${String(index + 1).padStart(8, '0')}`,
        department: departmentOptions[index % departmentOptions.length].value,
        position: `职位${index + 1}`,
        status: index % 3 === 0 ? 'inactive' : 'active',
        createTime: dayjs().subtract(index, 'day').format('YYYY-MM-DD HH:mm:ss'),
        lastLoginTime: index % 2 === 0 ? dayjs().subtract(index % 7, 'day').format('YYYY-MM-DD HH:mm:ss') : undefined,
      }));

      // 模拟筛选
      let filteredData = mockData;
      if (params.name) {
        filteredData = filteredData.filter(item => item.name.includes(params.name!));
      }
      if (params.department) {
        filteredData = filteredData.filter(item => item.department === params.department);
      }
      if (params.status) {
        filteredData = filteredData.filter(item => item.status === params.status);
      }

      // 模拟分页
      const start = (params.current - 1) * params.pageSize;
      const end = start + params.pageSize;
      const pageData = filteredData.slice(start, end);

      setDataSource(pageData);
      setPagination({
        current: params.current,
        pageSize: params.pageSize,
        total: filteredData.length,
      });
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除用户
  const handleDelete = async (id: string) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300));
      message.success('删除成功');
      // 重新加载数据
      fetchUsers({
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...searchForm.getFieldsValue(),
      });
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 保存用户（新增/编辑）
  const handleSave = async (values: UserFormData) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      if (editingUser) {
        message.success('编辑成功');
      } else {
        message.success('新增成功');
      }
      
      setModalVisible(false);
      setEditingUser(null);
      form.resetFields();
      
      // 重新加载数据
      fetchUsers({
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...searchForm.getFieldsValue(),
      });
    } catch (error) {
      message.error(editingUser ? '编辑失败' : '新增失败');
    }
  };

  // 搜索
  const handleSearch = (values: SearchFormData) => {
    fetchUsers({
      current: 1,
      pageSize: pagination.pageSize,
      ...values,
    });
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    fetchUsers({
      current: 1,
      pageSize: pagination.pageSize,
    });
  };

  // 打开编辑弹窗
  const handleEdit = (record: UserItem) => {
    setEditingUser(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 查看详情
  const handleView = (id: string) => {
    navigate(`/manual-crud/detail/${id}`);
  };

  // 表格列定义
  const columns: ColumnsType<UserItem> = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      fixed: 'left',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100,
      render: (value: string) => {
        const dept = departmentOptions.find(item => item.value === value);
        return dept?.label || value;
      },
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '活跃' : '非活跃'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 150,
      render: (time: string) => time || '-',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 初始化数据
  useEffect(() => {
    fetchUsers({
      current: 1,
      pageSize: 10,
    });
  }, []);

  return (
    <div style={{ padding: 24 }}>
      {/* 搜索表单 */}
      <Card title="搜索条件" style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          onFinish={handleSearch}
          layout="inline"
        >
          <Row gutter={16} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item name="name" label="姓名">
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="department" label="部门">
                <Select placeholder="请选择部门" allowClear>
                  {departmentOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="请选择状态" allowClear>
                  {statusOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 操作按钮 */}
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingUser(null);
              form.resetFields();
              setModalVisible(true);
            }}
          >
            新增用户
          </Button>
        </div>

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={dataSource}
          loading={loading}
          rowKey="id"
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
            onChange: (page, pageSize) => {
              fetchUsers({
                current: page,
                pageSize: pageSize || 10,
                ...searchForm.getFieldsValue(),
              });
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingUser(null);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入正确的邮箱格式' },
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="department"
                label="部门"
                rules={[{ required: true, message: '请选择部门' }]}
              >
                <Select placeholder="请选择部门">
                  {departmentOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="position"
                label="职位"
                rules={[{ required: true, message: '请输入职位' }]}
              >
                <Input placeholder="请输入职位" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  {statusOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button
                onClick={() => {
                  setModalVisible(false);
                  setEditingUser(null);
                  form.resetFields();
                }}
              >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingUser ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ManualUserList;